package deployr.core;

import static java.text.MessageFormat.*;

import java.io.*;
import java.net.*;

public class ProjectUpdate {

	private void addingProperties(HttpURLConnection connection) throws ProtocolException {
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestMethod("POST");
	}

	private HttpURLConnection createConnection(String url) throws IOException, MalformedURLException {
		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
		return connection;
	}

	public String createUpdate(String deployrUrl, String projectKey) {

		try {
			String url = format("{0}/projects/{1}/updates.yaml", deployrUrl, projectKey);
			HttpURLConnection createProjectUpdate = createConnection(url);
			addingProperties(createProjectUpdate);
			String json = read(createProjectUpdate);
			return json.replaceAll("^.*updateKey: ", "").replaceAll("}.*", "");
		} catch (Exception e) {
			err(e);
		}

		return "";
	}

	private void err(Exception e) {
		e.printStackTrace();
	}

	private String read(HttpURLConnection connection) throws IOException {
		OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
		writer.flush();
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String line;
		StringBuilder stringBuilder = new StringBuilder();
		while ((line = reader.readLine()) != null) {
			stringBuilder.append(line);
		}
		writer.close();
		reader.close();
		return stringBuilder.toString();
	}
}
